<template>
  <div>
    <el-drawer v-model="_isOpen" size="700" title="测量数据反馈" :direction="'rtl'" modal-class="measure-drawer">
      <template #header>
        <h4><i class="icon"></i>测量数据反馈</h4>
      </template>
      <template #default>
        <el-form :model="form" ref="formRef" :disabled="optionInfo.type === 'view'" label-width="auto" style="width: 100%">
          <el-form-item label="备注" prop="standardDesc">
            <el-input
              v-model="form.measureDataRemark"
              style="width: 100%"
              :rows="4"
              type="textarea"
              placeholder="请输入测量数据备注"
            />
          </el-form-item>
          <el-form-item label="附件" prop="picIdLen">
            <div>
              <!-- 上传附件 -->
              <el-upload
                v-if="!(optionInfo.type === 'view' && imgFileList.length <= 0)"
                class="upload-demo upload-card"
                :class="{ 'view-upload': optionInfo.type === 'view' }"
                v-model:file-list="imgFileList"
                :disabled="FileList.length >= 9"
                ref="uploadImg"
                :show-file-list="true"
                multiple
                :limit="9"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="
                  (file, fileList) => {
                    handleAvatarChangeIcon(file, fileList, 'file');
                  }
                "
              >
                <div :class="{ notuse: FileList.length >= 9 ? true : false }">
                  <el-icon class="f24"><Plus /></el-icon>
                  <p class="f12" style="line-height: 22px; color: #86909c">点击上传</p>
                </div>

                <template #file="{ file }">
                  <div class="jzt-flex-center" style="width: 100%; min-width: 80px">
                    <template v-if="file.file">
                      <video v-if="['mp4'].includes(getFileSuffix(file.file))" controls style="width: 125px; height: 100%">
                        <source :src="file.file" type="video/mp4" />
                        对不起，您的浏览器不支持播放视频文件
                      </video>
                      <el-image
                        v-else
                        class="el-upload-list__item-thumbnail"
                        :src="getUrl(file.file)"
                        :zoom-rate="1.2"
                        :max-scale="7"
                        :min-scale="0.2"
                        :preview-src-list="[getUrl(file.file)]"
                        fit="cover"
                        style="width: 80px; height: 100%"
                      />
                    </template>

                    <span v-show="!file.file" class="f30">
                      <el-icon><Loading /></el-icon>
                    </span>
                    <span class="el-upload-list__item-actions" v-if="optionInfo.type !== 'view'">
                      <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <el-icon><Delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
              <span v-else>--</span>
              <p v-if="optionInfo.type !== 'view'" class="f12" style="color: #86909c">
                支持上传CAD、PDF、Word、表格、图片、视频等格式
              </p>
            </div>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="info" class="jzt-button" @click="cancelClick">取消</el-button>
          <el-button v-if="optionInfo.type !== 'view'" type="primary" @click="confirmClick">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import {
  getFileName,
  getFileSuffix,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { Search } from "@element-plus/icons-vue";
import cad from "@/assets/images/CAD.png";
import excel from "@/assets/images/excel.png";
import word from "@/assets/word.png";
import pdf from "@/assets/pdf.png";

const emit = defineEmits(["update:isOpen", "submitOk"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        type: "add", //add edit view
        detail: {}
      };
    }
  }
});
const form = ref({});
const formRef = ref();
const _detail = ref({});

watch(
  () => props.optionInfo,
  val => {
    console.log("传递过来的测量数据反馈", val);

    _detail.value = {
      ...val.detail,
      // picIds: "",
      picUrls: val.detail.measureUrl
      // || "http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/mall/2024-11-14/flower1731576739028.mp4"
      // "http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/mall/2024-11-14/flower1731576739028.mp4,http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/mall/2024-11-14/CAD_file1731575720321.dwg,https://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/mall/2024-07-26/test1721986653087.docx,https://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/mall/2024-07-26/test%20-%20%E5%89%AF%E6%9C%AC1721986653626.pdf,https://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/mall/2024-07-26/2221721986654045.jpg"
    };

    form.value = {
      measureDataRemark: _detail.value.measureDataRemark
    };

    /**附件回显*/
    const imgList = [];
    // const imgIds = _detail.value.picIds ? _detail.value.picIds?.split(",") : [];
    const imgUrls = _detail.value.picUrls ? _detail.value.picUrls?.split(",") : [];
    for (let index in imgUrls) {
      imgList.push({
        url: imgUrls[index],
        file: imgUrls[index]
        // uid: imgIds[index] || ""
      });
    }
    imgFileList.value = imgList;
    FileList.value = imgList;
  },
  { deep: true, immediate: false }
);
const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

const getUrl = url => {
  const fileArr = ["doc", "docx"];
  const excelArr = ["xls", "xlsx"];
  const fileSuffix = getFileSuffix(url).toLowerCase() || "";
  const type = fileArr.includes(fileSuffix)
    ? "doc"
    : excelArr.includes(fileSuffix)
      ? "excel"
      : fileSuffix === "pdf"
        ? "pdf"
        : fileSuffix === "dwg"
          ? "cad"
          : "img";
  return type === "doc" ? word : type === "excel" ? excel : type === "pdf" ? pdf : type === "cad" ? cad : url;
};

const reset = () => {
  form.value = {};
  formRef.value.resetFields();
  FileList.value = [];
  imgFileList.value = [];
  videoList.value = [];
  videoListEdit.value = [];
};

const cancelClick = () => {
  _isOpen.value = false;
  reset();
  // emit("changeAttr");
};
const confirmClick = async () => {
  try {
    console.log("submitOk", imgFileList.value);
    emit("submitOk", {
      ..._detail.value,
      measureDataRemark: form.value.measureDataRemark,
      measureUrl: imgFileList.value.map(item => item.file)?.join(",")
    });
    _isOpen.value = false;
    reset();
  } catch (err) {
    console.log(err);
  }
};

defineExpose({});

//====================================图片上传========================================================================================
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { imgsUpload } from "@/apis/products/specifications";
import { ElMessage } from "element-plus";

const uploadImg = ref();
const uploadVideo = ref();
const FileList = ref([]); //商品图片list
const imgFileList = ref([]); //编辑时商品图片list
const videoList = ref([]); //商品视频list
const videoListEdit = ref([]); //编辑时商品视频list
// const imgIsReady = ref(false);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  let _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  const flag = await fileType(type, _fileList);
  if (!flag) {
    const errorFile = [];
    const successFile = [];
    if (type === "img") {
      ElMessage({
        message: "只能上传jpeg，jpg，png图片文件，大小不超过5M",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png") || item.raw.size > 1024 * 1024 * 5) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    } else if (type === "video") {
      ElMessage({
        message: "只能上传视频文件，并且视频时长不超过45秒，大小不超过100M",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (!(item.raw.type === "video/mp4") || item.raw.size > 1024 * 1024 * 100) {
          console.log(111, item, !item.raw.type === "video/mp4", item.raw.size > 1024 * 1024 * 200);
          errorFile.push(item);
        } else {
          console.log(222, item, !item.raw.type === "video/mp4", item.raw.size > 1024 * 1024 * 200);
          successFile.push(item);
        }
      }
      for (let item of errorFile) {
        uploadVideo.value.handleRemove(item);
      }
    } else if (type === "file") {
      ElMessage({
        message: "支持上传CAD、PDF、Word、表格、图片、视频等格式",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (
          !(
            item.raw.type === "image/jpeg" ||
            item.raw.type === "image/png" ||
            item.raw.type === "application/msword" ||
            item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
            item.raw.type === "application/pdf" ||
            item.raw.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
            item.raw.type === "application/vnd.ms-excel" ||
            getFileSuffix(item.name) === "dwg" ||
            item.raw.type === "video/mp4"
          )
        ) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    }

    fileList = successFile;
    if (successFile.length <= 0) return;
  }
  //   imgIsReady.value = false;
  if (type === "img" || type === "file") {
    FileList.value = fileList;
    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
  } else {
    videoList.value = fileList;

    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!((item.raw.type === "image/jpeg" || item.raw.type === "image/png") && item.raw.size <= 1024 * 1024 * 5)) {
        flag = false;
      }
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      // console.log("视频的大小===", item.raw.size);
      if (!(item.raw.type === "video/mp4" && item.raw.size <= 1024 * 1024 * 200)) {
        flag = false;
      }
      //   if (item.raw.type === "video/mp4") {
      //     await getTimes(item.raw);
      //     // console.log("视频的时长===", item.raw.size <= 1024 * 1024 * 100, videoTime.value);
      //     if (!(videoTime.value <= 45)) {
      //       flag = false;
      //     }
      //   }
    }
  } else if (type === "file") {
    for (let item of fileList) {
      if (
        !(
          item.raw.type === "image/jpeg" ||
          item.raw.type === "image/png" ||
          item.raw.type === "application/msword" ||
          item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
          item.raw.type === "application/pdf" ||
          item.raw.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          item.raw.type === "application/vnd.ms-excel" ||
          getFileSuffix(item.name) === "dwg" ||
          item.raw.type === "video/mp4"
        )
      ) {
        flag = false;
      }
    }
  }
  return flag;
};
/**
 * 获取视频时间长度
 */
const videoTime = ref(0);
const getTimes = async file => {
  let content = file;
  //获取录音时长
  let url = URL.createObjectURL(content);
  //经测试，发现audio也可获取视频的时长
  let audioElement = new Audio(url);
  console.log(2222);
  await new Promise((resolve, reject) => {
    audioElement.addEventListener("loadedmetadata", _event => {
      //保存获取时间长度
      videoTime.value = parseInt(audioElement.duration);
      resolve("时长获取成功");
    });
  });
};

const handleRemove = (file, type = "img") => {
  console.log("移除===", file);
  if (type === "img") {
    uploadImg.value.handleRemove(file);
    FileList.value = FileList.value.filter(item => item.uid !== file.uid);
  } else {
    uploadVideo.value.handleRemove(file);
    videoList.value = videoList.value.filter(item => item.uid !== file.uid);
  }
};

const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  console.log(111111, option, option.file.name);
  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl.split("?")[0]);
      if (type === "img") {
        item["img"] = res.fileUrl.split("?")[0];
      } else if (type === "video") {
        item["video"] = res.fileUrl.split("?")[0];
      } else {
        item["file"] = res.fileUrl.split("?")[0];
      }
      item["folder"] = objName;

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};

//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: option.file.folder, //目录＋文件名称
      url: option.file.img || option.file.video,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss">
.measure-drawer {
  .el-drawer {
    box-shadow: -8px 0px 16px 0px rgba(0, 38, 73, 0.1);
    border-radius: 10px 0px 0px 10px;
  }
  .el-drawer__header {
    font-size: 18px;
    color: #131414;
    padding-bottom: 20px !important;
    margin-bottom: 0 !important;
    border-bottom: 1px solid #dcdfe6;
    h4 {
      font-weight: normal;
      position: relative;
    }
  }
  .el-drawer__body {
    padding: 20 !important;

    .el-textarea.is-disabled {
      .el-textarea__inner {
        background-color: white;
      }
    }
  }
  .el-drawer__footer {
    display: flex;
    justify-content: flex-end;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    padding: 14px 20px;
  }
}
</style>
<style lang="scss" scoped>
:deep(.view-upload) {
  .el-upload.el-upload--picture-card {
    display: none;
  }
}
:deep(.upload-demo.upload-card) {
  .el-upload-list__item.is-ready,
  .el-upload-list__item.is-success {
    width: auto !important;
    height: 80px !important;
  }
}
:deep(.el-form-item) {
  flex-direction: column;
  .el-form-item__label-wrap {
    margin-left: 0 !important;
  }
}
.icon {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #409eff;
  margin: 0 10px 4px 0;
}
</style>
